import json

from django.http import JsonResponse
from django.shortcuts import render,redirect
from web.forms.wiki import WikiModelForm
from django.urls import reverse # 导入反向生成路由的模块
from web import models
from django.views.decorators.csrf import csrf_exempt
from utils.tencent.cos import put_object
from utils.encrypt import uid
from datetime import datetime
from django.core.files.storage import FileSystemStorage
from django.views.decorators.clickjacking import xframe_options_sameorigin
from web.models import Project


def wiki(request,project_id):
    """WIKI的首页"""
    # request.GET获取的是url中 ? 后面的参数和数据，例如：172.16.9.237:8007/web/manager/25/wiki/?wiki_id=12wiki_id=1 通过request.GET
    # 获取的数据是：<QueryDict: {'wiki_id': ['12']}>
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'manage/wiki.html')
    wiki_object = models.Wiki.objects.filter(id=wiki_id,project=project_id).first()
    return render(request,'manage/wiki.html',{'wiki_object':wiki_object})

def wiki_add(request,project_id):
    if request.method == 'GET':
        form = WikiModelForm(request)
        return render(request, 'manage/wiki_form.html', {'form':form})
    form = WikiModelForm(request,data=request.POST)
    if form.is_valid():
        # 需要先判断用户创建时，是否已经选择了父类，是的话需要把深度设为：depth=父类的depth + 1。
        # 可以根据表单中的字段parent是否有值来判断，是否选择了父节点
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('wiki',kwargs={'project_id':project_id})
        return redirect(url)
    return render(request, 'manage/wiki_form.html', {'form': form})

def wiki_catalog(request,project_id):
    """WIKI目录"""
    # .values_list 产生的数据是大列表中的一个个的元组，元组中包含"id","title","parent_id"对应的数据。.values产生的数据是一个大列表中的一个个的字典，
    # 其中"id","title","parent_id"是字典的键，对应的数据是字典的值
    # data = models.Wiki.objects.filter(project=request.tracer.project).values_list("id","title","parent_id")
    # 在数据表中添加深度页面，父类深度为1，子类为2，孙类为3，以此类推、逐渐增加。这样按照depth排列后，会首先创建深度为1的父类的标签li，
    # 再在父类完成创建后生成子类标签创建，子类创建完成后再生成孙类标签。这样就不会有先创建子类但是父类未创建从而导致子类无法创建的情况
    data = models.Wiki.objects.filter(project=request.tracer.project).values("id", "title", "parent_id").order_by('depth','id')
    return JsonResponse({'status':True,'data':list(data)})
# def wiki_detail(request,project_id):
#     """
#         查看文章详细页面： /detail?wiki_id = 1
#     :param request:
#     :param project_id:
#     :return:
#     """
#     pass
def wiki_delete(request,project_id,wiki_id):
    """删除文章"""
    models.Wiki.objects.filter(project_id=project_id,id=wiki_id).delete()
    ## 删除之后，利用反向路由跳转到wiki的主页面
    url = reverse('wiki', kwargs={'project_id': project_id})
    return redirect(url)

def wiki_edit(request,project_id,wiki_id):
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_object:
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)
    if request.method == 'GET':
        form = WikiModelForm(request,instance=wiki_object)
        return render(request,'manage/wiki_form.html',{'form':form})
    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('wiki',kwargs={'project_id':project_id})
        # 如果保存成功不要直接跳转到首页，应该是跳转到编辑完成的这个wiki_id的预览页面
        preview_url = "{0}?wiki_id={1}".format(url,wiki_id)
        return redirect(preview_url)
    return render(request, 'manage/wiki_form.html', {'form': form})


@csrf_exempt
@xframe_options_sameorigin
def wiki_upload(request,project_id):
    """mdeditor上传图片"""
    result = {
        'success': 0,
        'message': None,
        'url': None,
    }
    # 获取文件上传时的文件的对象
    image_object = request.FILES.get('editormd-image-file')
    if not image_object:
        result['message'] = "文件不存在"
        return JsonResponse(result)
    # # 获取本地上传文件的文件名，通过文件名中的 . 进行切割获取文件的后缀名。生成一个随机的文件名
    # ext = image_object.name
    # current_time = str(datetime.now().strftime("%Y%m%d-%H%M%S"))
    # key = "{}_{}".format(current_time,ext)
    # 也可以通过加密uuid来生成随机的文件名
    ext = image_object.name
    uuid = uid(str(datetime.now().strftime("%Y%m%d-%H%M%S")))
    key = "{}_{}".format(uuid, ext)
    # 把获取到的文件对象写入到桶中
    image_url = put_object(request.tracer.project.bucket,request.tracer.project.region,key,image_object)
    # 上传成功后需要通知md组件，通知的数据是固定格式
    result = {
        'success':1,
        'url':image_url,
        'message':None
    }
    return JsonResponse(result)
